/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { usePointContext } from './PointContext';
import { ChildLineCommandProps } from './types';

type FormDataType = {
  dxid?: pickedFaceData | pickedLineData;
};

export function PointCenter({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) {
  const [formData, setFormData] = useState<FormDataType>({
    dxid: null,
  });

  const { picker } = useTools();
  const { setSharedPoint } = usePointContext();

  useEffect(() => {
    executeData();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const dxid = props?.params?.dxid;

      await initEditDependency([dxid]);

      setFormData({
        dxid: picker.generatePickObjByPickID(dxid) as
          | pickedFaceData
          | pickedLineData,
      });
    }
  }, [editDxid, props]);

  const isFormDataValid = () => {
    const { dxid } = formData;
    return dxid !== null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await executeData(false);
    onClose();
  };

  const {
    previewCmdResult,
    initEditDependency,
    initingEdit,
    isLoading,
    clear,
    confirmCommand,
  } = useCommand('cmd-center-point', {
    onClose,
    finishDraw: checkAndFinishDraw,
    commandName: 'CreateVertex',
    editDxid: editDxid || props?.shape,
  });

  useEffect(() => {
    const pointdata = previewCmdResult?.data?.[0]?.points?.[0];
    if (pointdata) {
      setSharedPoint(pointdata);
    } else {
      setSharedPoint(null);
    }
  }, [previewCmdResult]);

  const errCallback = (err: any) => {
    if (err?.code == 601) {
      MessageTip.destroy();
      MessageTip.warning(
        '无效元素。所选元素不是圆、椭圆或球面。请选择圆、椭圆或球面。',
      );
    }
  };

  const executeData = async (preview: boolean = true) => {
    const { dxid } = formData;

    if (!isFormDataValid()) {
      clear();
      return;
    }

    const allParma = {
      a: {
        mode: 'center',
        dxid: getIdOfPickedObj(dxid),
      },
      p: preview,
    };

    await confirmCommand(allParma, preview, errCallback);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      dxid: {
        type: 'string',
        title: '圆/球面/椭圆',
        format: PickInputRJSFFormat.PickCurveSurface,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      onCancel={onClose}
      disabled={initingEdit}
      submitLoading={isLoading}
      isFormDataValid={isFormDataValid()}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          dxid: v.dxid,
        };
        setFormData(data);
      }}
      extraUiSchema={{
        dxid: {
          'ui:placeholder': '请输入曲线或曲面',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}
